package cn.bocweb.spinning.view.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.TrainRandomBean;
import cn.bocweb.spinning.model.Bean.TrainRandomKeysBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.activity.TrainActivity;
import de.greenrobot.event.EventBus;

/**
 * Created by chenchangxing on 15/12/26.
 */
public class TrainFragment extends Fragment implements View.OnClickListener {


    String ttype;
    String title;
    String right;
    List<String> option;
    String explain;
    String personRate;
    String allRate;

    UserPresenter userPresenter;

    TrainActivity trainActivity;
    Timer timer;
    String tid;
    int position, type, result, total;
    String userid, libtype, id, myWrong, myRight;
    boolean isCheckExplain, isVisible = false, isRight = false, isSelected = false;

    boolean isSelectAnswer = false;
    @Bind(R.id.train_type)
    TextView trainType;
    @Bind(R.id.train_title)
    TextView trainTitle;
    @Bind(R.id.train_select_icon_a)
    ImageView trainSelectIconA;
    @Bind(R.id.train_select_answer_a)
    TextView trainSelectAnswerA;
    @Bind(R.id.train_select_a)
    LinearLayout trainSelectA;
    @Bind(R.id.train_select_icon_b)
    ImageView trainSelectIconB;
    @Bind(R.id.train_select_answer_b)
    TextView trainSelectAnswerB;
    @Bind(R.id.train_select_b)
    LinearLayout trainSelectB;
    @Bind(R.id.train_select_icon_c)
    ImageView trainSelectIconC;
    @Bind(R.id.train_select_answer_c)
    TextView trainSelectAnswerC;
    @Bind(R.id.train_select_c)
    LinearLayout trainSelectC;
    @Bind(R.id.train_select_icon_d)
    ImageView trainSelectIconD;
    @Bind(R.id.train_select_answer_d)
    TextView trainSelectAnswerD;
    @Bind(R.id.train_select_d)
    LinearLayout trainSelectD;
    @Bind(R.id.train_select)
    LinearLayout trainSelect;
    @Bind(R.id.train_judge_icon_a)
    ImageView trainJudgeIconA;
    @Bind(R.id.train_judge_answer_a)
    TextView trainJudgeAnswerA;
    @Bind(R.id.train_judge_a)
    LinearLayout trainJudgeA;
    @Bind(R.id.train_judge_icon_b)
    ImageView trainJudgeIconB;
    @Bind(R.id.train_judge_answer_b)
    TextView trainJudgeAnswerB;
    @Bind(R.id.train_judge_b)
    LinearLayout trainJudgeB;
    @Bind(R.id.train_judge)
    LinearLayout trainJudge;
    @Bind(R.id.train_allrate)
    TextView trainAllrate;
    @Bind(R.id.sequence_wrong_people)
    TextView sequenceWrongPeople;
    @Bind(R.id.train_personrate)
    TextView trainPersonrate;
    @Bind(R.id.sequence_wrong_my_wrong)
    TextView sequenceWrongMyWrong;
    @Bind(R.id.sequence_wrong_my_right)
    TextView sequenceWrongMyRight;
    @Bind(R.id.train_explain_rate)
    LinearLayout trainExplainRate;
    @Bind(R.id.train_explain)
    TextView trainExplain;
    @Bind(R.id.train_explain_detail)
    LinearLayout trainExplainDetail;
    @Bind(R.id.sequence_wrong_layout)
    LinearLayout sequenceWrongLayout;
    @Bind(R.id.sequence_explain_explain)
    TextView sequenceExplainExplain;
    @Bind(R.id.sequence_explain_detail)
    LinearLayout sequenceExplainDetail;
    @Bind(R.id.sequence_explain_allrate)
    TextView sequenceExplainAllrate;
    @Bind(R.id.sequence_explain_people_wrong)
    TextView sequenceExplainPeopleWrong;
    @Bind(R.id.sequence_explain_personrate)
    TextView sequenceExplainPersonrate;
    @Bind(R.id.sequence_explain_my_wrong)
    TextView sequenceExplainMyWrong;
    @Bind(R.id.sequence_explain_my_right)
    TextView sequenceExplainMyRight;
    @Bind(R.id.sequence_explain_rate)
    LinearLayout sequenceExplainRate;
    @Bind(R.id.sequence_explain_layout)
    LinearLayout sequenceExplainLayout;
    @Bind(R.id.train_title_layout)
    LinearLayout trainTitleLayout;

    Timer timer1;


    public TrainFragment(int position, int type, String userid, String libtype, int total) {

        this.position = position;
        this.type = type;
        this.userid = userid;
        this.libtype = libtype;
        this.total = total;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_train_select, container, false);
        ButterKnife.bind(this, view);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        timer = new Timer();
        userPresenter = new UserPresenterImp();
        trainActivity = (TrainActivity) getActivity();

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (isVisible) {
            if(!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    switch (type) {
                        case Constant.TRAIN_RANDOM: {

                            userPresenter.trainRandom(String.valueOf(position + 1), libtype, userid, "0");
                            break;
                        }
                        case Constant.TRAIN_ERROR: {
                            userPresenter.errorTrain(String.valueOf(position + 1), libtype, userid);
                            break;
                        }
                        case Constant.TRAIN_DIFF: {
                            userPresenter.hardTrain(String.valueOf(position + 1), libtype, userid);
                            break;
                        }
                    }
                }
            };
            if (timer1 == null) {
                timer1 = new Timer();
            }
            timer1.schedule(timerTask, 500);
        } else {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
        if (timer != null) {
            timer.cancel();
            timer.purge();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer1 != null) {
            timer.cancel();
            timer.purge();
        }
    }

    public String getTId() {
        return id;
    }

    public int getResult() {
        return result;
    }

    public int getType() {
        return type;
    }

    public String getUserid() {
        return userid;
    }

    public String getLibtype() {
        return libtype;
    }

    public boolean isRight() {
        return isRight;
    }

    public void onEventMainThread(TrainRandomBean bean) {
        if (isVisible) {
            if (bean.getReturn_code() == 0) {

                if (trainActivity == null) {
                    trainActivity = (TrainActivity) getActivity();
                }
                trainActivity.isCollect(bean.getRecord().getIsCollect().equals("1"));
                tid = bean.getData().getId();
                ttype = bean.getData().getTtype();
                option = bean.getData().getOption();
                right = bean.getData().getRight();
                title = bean.getData().getTitle();
                id = bean.getData().getId();

                allRate = bean.getRecord().getAllrate();

                if (bean.getRecord().getPersonrate() != null) {
                    personRate = bean.getRecord().getPersonrate();
                } else {
                    personRate = "0";
                }
                explain = bean.getRecord().getExplain();
                if (bean.getRecord().getWrong_times() != null) {
                    myWrong = bean.getRecord().getWrong_times();
                } else {
                    myWrong = "0";
                }
                if (bean.getRecord().getOk_times() != null) {
                    myRight = bean.getRecord().getOk_times();
                } else {
                    myRight = "0";
                }

                initType();
                initOptions();
                initTitle();

                if (isSelected) {
                    switch (bean.getData().getTtype()) {
                        case "1": {
                            initSelectResult(result);
                            break;
                        }
                        case "2": {
                            initJudgeResult(result);
                            break;
                        }
                    }
                    if (!isCheckExplain) {
                        trainExplain.setText(explain);
                        trainAllrate.setText(allRate + "%");
                        trainPersonrate.setText(personRate + "%");
                        sequenceWrongMyRight.setText(myRight);
                        sequenceWrongMyWrong.setText(myWrong);
                        sequenceWrongPeople.setText(allRate + "%");

                        sequenceWrongLayout.setVisibility(View.VISIBLE);
                        sequenceExplainLayout.setVisibility(View.GONE);

                    } else {
                        sequenceExplainPersonrate.setText(personRate + "%");
                        sequenceExplainAllrate.setText(allRate + "%");
                        sequenceExplainExplain.setText(explain);
                        sequenceExplainPeopleWrong.setText(allRate + "%");
                        sequenceExplainMyRight.setText(myRight);
                        sequenceExplainMyWrong.setText(myWrong);

                        sequenceWrongLayout.setVisibility(View.GONE);
                        sequenceExplainLayout.setVisibility(View.VISIBLE);
                    }
                } else {
                    initClickBtn();
                }
            } else if (bean.getReturn_code() == -206) {
                DeviceUtil.Log(bean.getMsg());
            }
        }
    }

    public void onEventMainThread(TrainRandomKeysBean bean) {
        if (isVisible) {
            if (bean.getReturn_code() == 0) {

                allRate = bean.getData().getAllrate();
                if (bean.getData().getPersonrate() != null) {
                    personRate = bean.getData().getPersonrate();
                } else {
                    personRate = "0";
                }
                explain = bean.getData().getExplain();
                if (bean.getData().getWrong_times() != null) {
                    myWrong = bean.getData().getWrong_times();
                } else {
                    myWrong = "0";
                }
                if (bean.getData().getOk_times() != null) {
                    myRight = bean.getData().getOk_times();
                } else {
                    myRight = "0";
                }

                trainExplain.setText(explain);
                trainAllrate.setText(allRate + "%");
                trainPersonrate.setText(personRate + "%");
                sequenceWrongMyRight.setText(myRight);
                sequenceWrongMyWrong.setText(myWrong);
                sequenceWrongPeople.setText(allRate + "%");

                sequenceExplainLayout.setVisibility(View.GONE);
                sequenceWrongLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initType() {
        trainTitleLayout.setVisibility(View.VISIBLE);
        if (!(ttype == null || ttype.isEmpty())) {
            switch (Integer.parseInt(ttype)) {
                case 1: {
                    trainType.setText("选");
                    trainSelect.setVisibility(View.VISIBLE);
                    trainJudge.setVisibility(View.GONE);
                    break;
                }
                case 2: {
                    trainType.setText("判");
                    trainSelect.setVisibility(View.GONE);
                    trainJudge.setVisibility(View.VISIBLE);
                    break;
                }
                default: {
                    // TODO: 16/1/25 这里要做成下拉刷新
                }
            }
        }
    }

    private void initOptions() {
        if (!(option == null || option.isEmpty())) {
            trainSelectAnswerA.setText(option.get(0));
            trainSelectAnswerB.setText(option.get(1));
            trainSelectAnswerC.setText(option.get(2));
            trainSelectAnswerD.setText(option.get(3));
        }
    }

    private void initTitle() {
        trainTitle.setText(title);
    }

    private void initClickBtn() {
        trainSelectA.setOnClickListener(this);
        trainSelectB.setOnClickListener(this);
        trainSelectC.setOnClickListener(this);
        trainSelectD.setOnClickListener(this);
        trainJudgeA.setOnClickListener(this);
        trainJudgeB.setOnClickListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public String getTtype() {
        return ttype;
    }

    public void setTtype(String ttype) {
        this.ttype = ttype;
//        if (type == 3) {
        initType();
//        }
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
//        if (type == 3) {
        trainTitle.setText(title);
//        }
    }

    public String getRight() {
        return right;
    }

    public void setRight(String right) {
        this.right = right;
    }


    public void setExplain(String explain) {
        trainExplain.setText(explain);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.train_select_a: {
                initSelectResult(1);
                trainActivity.addQuizChoose(position, 1);
                checkIsAllAnswer();
                break;
            }
            case R.id.train_select_b: {

                initSelectResult(2);
                trainActivity.addQuizChoose(position, 2);
                checkIsAllAnswer();

                break;
            }
            case R.id.train_select_c: {
                initSelectResult(3);
                trainActivity.addQuizChoose(position, 3);
                checkIsAllAnswer();

                break;
            }
            case R.id.train_select_d: {
                initSelectResult(4);
                trainActivity.addQuizChoose(position, 4);
                checkIsAllAnswer();

                break;
            }
            case R.id.train_judge_a: {
                initJudgeResult(1);
                trainActivity.addQuizChoose(position, 1);
                checkIsAllAnswer();

                break;
            }
            case R.id.train_judge_b: {
                initJudgeResult(2);
                trainActivity.addQuizChoose(position, 2);
                checkIsAllAnswer();

                break;
            }
        }
    }

    private void checkIsAllAnswer() {
        if (trainActivity.isAllAnswer()) {
            AlertDialog.Builder build = new AlertDialog.Builder(getActivity());
            build.setTitle("提示");
            build.setMessage("您已做完所有题目,是否退出");
            build.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    trainActivity.finish();
                }
            });
            build.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            build.show();
        }
    }


    private void initSelectResult(int result) {
        isSelectAnswer = true;
        trainSelectA.setClickable(false);
        trainSelectB.setClickable(false);
        trainSelectC.setClickable(false);
        trainSelectD.setClickable(false);
        trainJudgeA.setClickable(false);
        trainJudgeB.setClickable(false);

        this.result = result;
        int selectAnswer = Integer.parseInt(right);
        if (result == selectAnswer) {

            if (!isSelected) {
                switch (type) {
                    case 1: {
                        userPresenter.trainRandomKeys(String.valueOf(position + 1), id, ttype, libtype, "1", String.valueOf(result), userid);
                        break;
                    }
                    case 2: {
                        userPresenter.errorKeys(String.valueOf(position + 1), id, ttype, libtype, "1", String.valueOf(result), userid);
                        break;
                    }
                    case 3: {
                        userPresenter.hardKeys(String.valueOf(position + 1), id, ttype, libtype, "1", userid);
                        break;
                    }
                }

                if (!trainActivity.isAllAnswer()) {
                    if (position < total - 1) {
                        trainActivity.addQuizCorrect(position, true);
                        TimerTask timerTask = new TimerTask() {
                            @Override
                            public void run() {
                                trainActivity.selectRightAnswer(position + 1);
                            }
                        };
                        timer.schedule(timerTask, 1000);
                        DeviceUtil.MyToast(getActivity(), Constant.ANSWER_RIGHT);
                    }
                }
            }
            switch (result) {
                case 1: {
                    trainSelectIconA.setImageResource(R.mipmap.exam_answer_right);
                    break;
                }
                case 2: {
                    trainSelectIconB.setImageResource(R.mipmap.exam_answer_right);
                    break;
                }
                case 3: {
                    trainSelectIconC.setImageResource(R.mipmap.exam_answer_right);
                    break;
                }
                case 4: {
                    trainSelectIconD.setImageResource(R.mipmap.exam_answer_right);
                    break;
                }
            }
        } else {
            if (!isSelected) {
                switch (type) {
                    case 1: {
                        userPresenter.trainRandomKeys(String.valueOf(position + 1), id, ttype, libtype, "0", String.valueOf(result), userid);
                        break;
                    }
                    case 2: {
                        userPresenter.errorKeys(String.valueOf(position + 1), id, ttype, libtype, "0", String.valueOf(result), userid);
                        break;
                    }
                    case 3: {
                        userPresenter.hardKeys(String.valueOf(position + 1), id, ttype, libtype, "0", userid);
                        break;
                    }
                }
            }
            trainActivity.addQuizCorrect(position, false);
            switch (selectAnswer) {
                case 1: {
                    drawSelectResult(trainSelectIconA);
                    break;
                }
                case 2: {
                    drawSelectResult(trainSelectIconB);
                    break;
                }
                case 3: {
                    drawSelectResult(trainSelectIconC);
                    break;
                }
                case 4: {
                    drawSelectResult(trainSelectIconD);
                    break;
                }
            }
        }
        isSelected = true;
    }

    private void drawSelectResult(ImageView select) {
        trainSelectIconA.setImageResource(R.mipmap.exam_answer_wrong);
        trainSelectIconB.setImageResource(R.mipmap.exam_answer_wrong);
        trainSelectIconC.setImageResource(R.mipmap.exam_answer_wrong);
        trainSelectIconD.setImageResource(R.mipmap.exam_answer_wrong);

        select.setImageResource(R.mipmap.exam_answer_right);
    }

    private void initJudgeResult(int result) {
        isSelectAnswer = true;
        trainJudgeA.setClickable(false);
        trainJudgeB.setClickable(false);
        trainSelectA.setClickable(false);
        trainSelectB.setClickable(false);
        trainSelectC.setClickable(false);
        trainSelectD.setClickable(false);

        this.result = result;
        int judgeAnswer = Integer.parseInt(right);
        if (result == judgeAnswer) {
            if (!isSelected) {
                switch (type) {
                    case 1: {
                        userPresenter.trainRandomKeys(String.valueOf(position + 1), id, ttype, libtype, "1", String.valueOf(result), userid);
                        break;
                    }
                    case 2: {
                        userPresenter.errorKeys(String.valueOf(position + 1), id, ttype, libtype, "1", String.valueOf(result), userid);
                        break;
                    }
                    case 3: {
                        userPresenter.hardKeys(String.valueOf(position + 1), id, ttype, libtype, "1", userid);
                        break;
                    }
                }

                if (!trainActivity.isAllAnswer()) {
                    if (position < total - 1) {
                        TimerTask timerTask = new TimerTask() {
                            @Override
                            public void run() {
                                trainActivity.selectRightAnswer(position + 1);
                            }
                        };
                        timer.schedule(timerTask, 1000);
                        DeviceUtil.MyToast(getActivity(), Constant.ANSWER_RIGHT);
                    }
                }
            }
            trainActivity.addQuizCorrect(position, true);

            switch (result) {
                case 1: {
                    trainJudgeIconA.setImageResource(R.mipmap.exam_answer_right);
                    break;
                }
                case 2: {
                    trainJudgeIconB.setImageResource(R.mipmap.exam_answer_right);
                    break;
                }
            }
        } else {
            if (!isSelected) {
                switch (type) {
                    case 1: {
                        userPresenter.trainRandomKeys(String.valueOf(position + 1), id, ttype, libtype, "0", String.valueOf(result), userid);
                        break;
                    }
                    case 2: {
                        userPresenter.errorKeys(String.valueOf(position + 1), id, ttype, libtype, "0", String.valueOf(result), userid);
                        break;
                    }
                    case 3: {
                        userPresenter.hardKeys(String.valueOf(position + 1), id, ttype, libtype, "0", userid);
                        break;
                    }
                }
            }
            trainActivity.addQuizCorrect(position, false);
            switch (judgeAnswer) {
                case 1: {
                    drawJudgeRuselt(trainJudgeIconA);
                    break;
                }
                case 2: {
                    drawJudgeRuselt(trainJudgeIconB);
                    break;
                }
            }
        }
        isSelected = true;
    }

    @Override
    public void onPause() {
        super.onPause();

    }

    public void showDetail() {
        sequenceExplainAllrate.setText(allRate + "%");
        sequenceExplainExplain.setText(explain);
        sequenceExplainMyRight.setText(myRight);
        sequenceExplainMyWrong.setText(myWrong);
        sequenceExplainPeopleWrong.setText(allRate + "%");
        sequenceExplainPersonrate.setText(personRate + "%");

        sequenceWrongLayout.setVisibility(View.GONE);
        sequenceExplainLayout.setVisibility(View.VISIBLE);

        isCheckExplain = !isCheckExplain;
    }

    private void drawJudgeRuselt(ImageView judge) {
        trainJudgeIconA.setImageResource(R.mipmap.exam_answer_wrong);
        trainJudgeIconB.setImageResource(R.mipmap.exam_answer_wrong);

        judge.setImageResource(R.mipmap.exam_answer_right);
    }

    public String getTid() {
        return tid;
    }


}
